package com.kbbywyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.kbbywyclient.R;
import com.kbbywyclient.app.App;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.app.Key;
import com.kbbywyclient.callback.WeChatPayCallback;
import com.kbbywyclient.data.entity.UnionPayInfo;
import com.kbbywyclient.data.entity.WeChatPayParams;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.presenter.RechargePresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.RechargeContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.MD5Utils;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomToolBar;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.util.HashMap;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by cbb on 2017/4/17.
 */

public class RechargeFailureActivity extends BaseActivity implements RechargeContract.View,WeChatPayCallback{
    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.bt_try_again)
    Button bt_try_again;
    @BindView(R.id.bt_contact_clerk)
    Button bt_contact_clerk;

    @Inject
    RechargePresenter presenter;

    private int chargeAmount=300;//充值金额，默认为300
    private int payType=1;//支付方式 1微信 2银联支付 默认为微信支付
    private String CompanyID="";
    private String CompanyTypeID="";

    private IWXAPI iwxapi;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_recharge_failure;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("充值失败");
    }

    @Override
    protected void initView() {
        iwxapi= WXAPIFactory.createWXAPI(this, Key.weChatAppId);
        App.getInstance().weChatPayCallback=this;
        v_toolbar.setLeftViewOnClickLinster(v -> finish());
    }

    @Override
    public void initData() {
        Intent intent=getIntent();
        chargeAmount=intent.getIntExtra("chargeAmount",300);
        payType=intent.getIntExtra("payType",1);
        CompanyID=intent.getStringExtra("CompanyID");
        CompanyTypeID=intent.getStringExtra("CompanyTypeID");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data!=null){
            String msg=data.getExtras().getString("pay_result");
            if("success".equalsIgnoreCase(msg)){
                toReChargeSuccessActivity();
            }else if("failure".equalsIgnoreCase(msg)){
                handlePayFailure();
            }else if("cancel".equalsIgnoreCase(msg)){
                handlePayCancel();
            }
        }
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {

    }

    @OnClick({R.id.bt_try_again,R.id.bt_contact_clerk})
    void onClick(View view){
        switch (view.getId()){
            case R.id.bt_try_again:
                //再试一次
                if(payType== Constants.PAY_TYPE_WE_CHAT){
                    presenter.getWeChatPayInfo(String.valueOf(PreUtils.getUser(this).getSalesID()),
                            MD5Utils.md5(StringUtil.getDeviceId(this)),
                            "1",
                            String.valueOf(chargeAmount));
                }else if(payType==Constants.PAY_TYPE_UNION){
                    presenter.getUnionPayInfo(String.valueOf(PreUtils.getUser(this).getSalesID()),
                            MD5Utils.md5(StringUtil.getDeviceId(this)),
                            "1",
                            String.valueOf(chargeAmount));
                }
                break;
            case R.id.bt_contact_clerk:
                //联系业务顾问
                break;
        }
    }



    //去往支付成功后的页面
    private void toReChargeSuccessActivity(){
        HashMap<String,Object> map=new HashMap<>();
        map.put("chargeAmount",chargeAmount);
        map.put("CompanyID", CompanyID);
        map.put("CompanyTypeID", CompanyTypeID);
        ActivitySkipUtil.skipAnotherActivity(this,RechargeSuccessActivity.class,map);
        finish();
    }

    //处理支付失败，暂时只显示Toast，提醒用户支付失败
    private void handlePayFailure(){
        ToastUtil.showShort("支付失败,请稍后重试");
    }

    //处理支付取消，暂时只显示Toast，提醒用户支付取消
    private void handlePayCancel(){
        ToastUtil.showShort("您取消了支付");
    }

    @Override
    public void onDestroy() {
        //将application中持有的此activity引用释放掉
        App.getInstance().weChatPayCallback=null;
        super.onDestroy();
    }

    @Override
    public void onWeChatPaySuccess() {
        toReChargeSuccessActivity();
    }

    @Override
    public void onWeChatPayFailure() {
        handlePayFailure();
    }

    @Override
    public void onWeChatPayCancel() {
        handlePayCancel();
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void onGetWeChatPayInfoSuccess(WeChatPayParams weChatPayParams) {
        if("1".equals(weChatPayParams.getStatus())){
            //成功，唤起微信支付
            final PayReq payReq=new PayReq();
            payReq.appId=weChatPayParams.getAppId();
            payReq.partnerId=weChatPayParams.getPartnerId();
            payReq.prepayId=weChatPayParams.getPrepayId();
            payReq.nonceStr=weChatPayParams.getNonceStr();
            payReq.timeStamp=weChatPayParams.getTimeStamp();
            payReq.packageValue=weChatPayParams.getPackageValue();
            payReq.sign=weChatPayParams.getSign();
            payReq.extData=getClass().getName();
            boolean call=iwxapi.sendReq(payReq);
            LogUtil.d("调用微信支付结果:"+call);
        }else{
            //失败
            ToastUtil.showLong(weChatPayParams.getMsg());
        }
    }

    @Override
    public void onGetUnionPayInfoSuccess(UnionPayInfo unionPayInfo) {
        String msg=unionPayInfo.getMsg();
        if("1".equals(unionPayInfo.getStatus())){
            //正式环境00 测试环境01
            UPPayAssistEx.startPay(this,null,null,msg,"00");
        }else{
            if(!TextUtils.isEmpty(msg)){
                ToastUtil.showLong(msg);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("chargeAmount",chargeAmount);
        outState.putInt("payType",payType);
        outState.putString("CompanyID",CompanyID);
        outState.putString("CompanyTypeID",CompanyTypeID);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        chargeAmount=savedInstanceState.getInt("chargeAmount");
        payType=savedInstanceState.getInt("payType");
        CompanyID=savedInstanceState.getString("CompanyID");
        CompanyTypeID=savedInstanceState.getString("CompanyTypeID");
    }
}
